<?php
// +----------------------------------------------------------------------
// | 优惠券相关处理       D:20150825   M:501468940
// +----------------------------------------------------------------------
include('/var/www/html/new/com.inc.php');
include('/var/www/html/new/d/class/abc/Validate.class.php');


if(!isset($_SESSION['sid'])) Response('{"status":"fail","msg":"登陆超时","code":0}');


switch(trim($_REQUEST['action'])){
	
	// 创建优惠券
	case 'coupon_create':
		$recData = abc777\Validate::addslashes($_REQUEST);
		$insData = insData_build($recData);
		
		if($insData['coupon_value']<=0) Response('{"status":"fail","msg":"优惠券面额不能小于或等于0"}');
		if($insData['condition']<=0)    Response('{"status":"fail","msg":"消费额度不能小于或等于0"}');
		if($insData['coupon_value']>$insData['condition']) Response('{"status":"fail","msg":"消费额度不能小于优惠面额"}');
		
		if($insData['nums']<=0)         Response('{"status":"fail","msg":"发行数量不能小于1"}');
		if($insData['collect_limit']<=0)Response('{"status":"fail","msg":"限领张数不能小于1"}');
		if($insData['effective_type']==1 && ($insData['use_startdate']=='')) {
			Response('{"status":"fail","msg":"请填写优惠券有效开始日期"}');
		}
        if($insData['effective_type']>1 && !$insData['pid']) 
		{
            Response('{"status":"fail","msg":"自动发放的优惠券必须选择一个产品"}');
        }
		
		if($insData['effective_type']==1 || $insData['effective_type']==3){
			if(strtotime($insData['use_enddate']) < strtotime($insData['collect_enddate']))
			{
				Response('{"status":"fail","msg":"有效期结束时间必须大于或等于领取结束时间"}');
			}
		}

		
		$coupon_id = $_REQUEST['id'] + 0;
		if($coupon_id==0){
			$sql = _insertSqlBuild($insData, 'pft_coupons');
			if($GLOBALS['le']->query($sql)) Response('{"status":"success","msg":"发布成功"}');
			exit('{"status":"success","msg":"发布失败"}');
		}else{
			
			unset($insData['create_time']);
			$insData['modify_time'] = date('Y-m-d H:i:s');
			$sql = _updateSqlBuild($insData, 'pft_coupons');
			$sql.=" where id=$coupon_id limit 1";
			if($GLOBALS['le']->query($sql)) Response('{"status":"success","msg":"编辑成功"}');
			Response('{"status":"success","msg":"编辑失败"}');
		}
		break;
	// 根据ID获取优惠券
	case 'coupon_list':
		$memberSID = $_SESSION['sid'];
		$coupon_id = $_REQUEST['id'] + 0;
		$status    = $_REQUEST['status'] + 0;
		if($coupon_id>0){
			$sql = "select * from pft_coupons where id=$coupon_id and apply_did=$memberSID limit 1";
			$GLOBALS['le']->query($sql);
			while($row=$GLOBALS['le']->fetch_assoc()) $dbRow[] = $row;
			$last  = 1;
			$total = 1;
		}else{
			// 分页
			$currentPage = $_REQUEST['last'] ? $_REQUEST['last']+0:1;
			$pageSize    = $_REQUEST['pageSize'] ? $_REQUEST['pageSize']+0:15;
			$startPos    = ($currentPage-1) * $pageSize;
			$condition   = " and status=$status";
			if(isset($_REQUEST['title']) && $_REQUEST['title']){
				$title = addslashes($_REQUEST['title']);
				$condition.= ' and coupon_name like "%'.$title.'%"';
			}

			$sql = "select * from pft_coupons where apply_did=$memberSID $condition limit $startPos,$pageSize";
			$GLOBALS['le']->query($sql);
			while($row=$GLOBALS['le']->fetch_assoc()) $dbRow[] = $row;
			
			$sql = "select count(id) as c from pft_coupons where apply_did=$memberSID $condition";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			$total = ceil($GLOBALS['le']->f('c') / $pageSize);
			$last  = $currentPage+1;
			if($last>$total) $last = '';
		}
		Response(json_encode(array('status'=>'success','list'=>$dbRow, 'totalPage'=>$total, 'last'=>$last)));
		break;
	// 更改优惠券的状态
	case 'coupon_ch_state':
		$coupon_id = $_REQUEST['id'] + 0;
		$status_s  = $_REQUEST['status'] + 0;
		$status_t  = array('正常', '下架', '过期');
		$sql = "select id,status,apply_did from pft_coupons where id=$coupon_id limit 1";
		$GLOBALS['le']->query($sql);
		$dbRow = $GLOBALS['le']->fetch_assoc();
		if(!$dbRow) Response('{"status":"fail","msg":"参数错误"}');
		if($dbRow['apply_did']!=$_SESSION['sid']) exiResponset('{"status":"fail","msg":"参数错误"}');
		if($status_s==0 && $dbRow['status']!=1) Response('{"status":"fail","msg":"状态出错"}');
		if($status_s==1 && $dbRow['status']!=0) Response('{"status":"fail","msg":"状态出错"}');
		
		$sql = "update pft_coupons set status=$status_s where id=$coupon_id limit 1";
		if($GLOBALS['le']->query($sql)) Response('{"status":"success","msg":"执行成功"}');
		Response('{"status":"success","msg":"执行失败"}');
		break;
	// 显示产品名称
	case 'coupon_prods':
		$pid_s = $_REQUEST['pid'];
		$pid_a = explode(',', $pid_s); $response = array();
		$sql = "select t.title as ttitle,t.pid,l.title as ltitle from uu_jq_ticket t inner join uu_land l on l.id=t.landid inner join uu_products p on p.id=t.pid where p.id in ($pid_s) limit ".count($pid_a);
		$GLOBALS['le']->query($sql);
		while($row=$GLOBALS['le']->fetch_assoc()) $response[] = $row;
		// exit(json_encode(array('status'=>'success','list'=>$response)));
		Response(json_encode(array('status'=>'success','list'=>$response)));
		break;
	// 优惠券关联产品
	case 'coupon_pid_relation':
		$pid_s     = $_REQUEST['pid'];
		$coupon_id = $_REQUEST['id'] + 0;
		$sql = "update pft_coupons set pid='$pid_s' where id=$coupon_id and apply_did={$_SESSION['sid']} limit 1";
		if($GLOBALS['le']->query($sql)) Response('{"status":"success","msg":"执行成功"}');//exit('{"status":"success","msg":"执行成功"}');
		Response('{"status":"success","msg":"执行失败"}');
		// exit('{"status":"success","msg":"执行失败"}');
		break;
	default:exit('{"status":"fail","msg":"参数错误"}');break;
}


function insData_build($recData){
	$insData = array();
	$insData['coupon_name']   = $recData['coupon_name'];    // 优惠券名称
	$insData['coupon_value']  = $recData['coupon_value'] * 100; // 优惠面额
	$insData['use_startdate'] = date('Y-m-d 00:00:00', strtotime($recData['effective_start']));// 有效期开始时间
	$insData['use_enddate']   = date('Y-m-d 23:59:59', strtotime($recData['effective_end']));  // 有效期结束时间
	$insData['effective_type']= $recData['e_type'];         // 有效期判断类型 0 领取日当天有效 1 设定的时间段
    if ($recData['auto_send']==1) {
        $insData['effective_type'] += 2;//2领取日当天有效且自动发放 3设定时间段有效且自动发放
    }
//    print_r($insData);
//    exit;
	// if($recData['e_type']==0){
		// $insData['use_startdate'] = '';
		// $insData['use_enddate']   = '';
	// }
	$insData['condition']     = $recData['condition'] * 100;      // 消费条件 消费多少可使用
	$insData['limit_use']     = $recData['use_limit'];      // 优惠券使用限制 0 不限 1 一次1张 2 随门票总数
	
	if($recData['use_channel']) 
		$insData['channel'] = implode(',', $recData['use_channel']);    // 使用渠道 0 不限 1 微信  2 二级店铺 3 自助机
	
	$insData['nums']          = $recData['nums'];           // 发行数量, -1 表示不限
	$insData['pid']           = $recData['pid'];            // 使用的产品PID    1,2,3,5,
	$insData['collect_startdate'] = date('Y-m-d 00:00:00', strtotime($recData['collect_startdate']));// 领取开始时间
	$insData['collect_enddate']   = date('Y-m-d 23:59:59', strtotime($recData['collect_enddate']));  // 领取结束时间
	$insData['collect_limit']     = $recData['collect_limit']+0;    // 限领张数
	$insData['create_time']       = date('Y-m-d');
	$insData['apply_did']         = $_SESSION['sid'];
	return $insData;
}

function Response($text){
	$GLOBALS['le']->close();
	exit("$text");
}

// 生成语句
function _insertSqlBuild($data, $table){
	if(is_null($data)) return '';
	$sql = 'insert into `'.$table.'` set ';
	foreach($data as $field=>$value){
		$sql = $sql.'`'.$field.'`="'.$value.'",';
	}
	return rtrim($sql,',');
}
// 生成编辑语句
function _updateSqlBuild($data, $table){
	if(is_null($data)) return '';
	$sql = 'update `'.$table.'` set ';
	foreach($data as $field=>$value){
		$sql = $sql.'`'.$field.'`="'.$value.'",';
	}
	$sql = rtrim($sql,',');
	return $sql;
}
